package com.androidcourse.changeandget.Adapt;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;


import com.androidcourse.changeandget.R;
import com.androidcourse.changeandget.User.Good;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class GoodAdapt extends BaseAdapter {
    private Context context;
    private LayoutInflater layoutInflater;

    private List<Good> collections = new ArrayList<>();

    HashMap<Integer,View> location = new HashMap<>();
    public GoodAdapt(Context context) {
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    public void setData(List<Good> collections) {
        this.collections = collections;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return collections.size();
    }

    @Override
    public Object getItem(int position) {
        return collections.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if(location.get(position) == null){
            convertView = layoutInflater.inflate(R.layout.goodinformation,null);
            Good commodity = (Good) getItem(position);
            holder = new ViewHolder(convertView,commodity);
            location.put(position,convertView);
            convertView.setTag(holder);
        }else{
            convertView = location.get(position);
            holder = (ViewHolder) convertView.getTag();
        }
        return convertView;
    }

    static class ViewHolder {
        ImageView ivCommodity;
        TextView tvTitle,tvDescription,tvid,tvPhone;


        public ViewHolder(View itemView,Good collection) {
            tvTitle = itemView.findViewById(R.id.tv_name);
            tvDescription = itemView.findViewById(R.id.tv_description);
            ivCommodity = itemView.findViewById(R.id.iv_commodity);
            tvid=itemView.findViewById(R.id.tv_id);

            tvTitle.setText(collection.getGname());
            tvDescription.setText(collection.getDGood());
            tvid.setText(collection.getGID());
            byte[] picture = collection.getImage();

            Bitmap img = BitmapFactory.decodeByteArray(picture,0,picture.length);
            ivCommodity.setImageBitmap(img);
        }
    }
}
